/**
 * 
 */
package com.cipe.cmrs.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cipe.cmrs.model.User;
import com.cipe.cmrs.util.PasswordEncryptionUtil;
import com.cipe.cmrs.util.Util;

/**
 * @author Incepio
 * 
 */

@Service
@Transactional
public class UserService extends BaseService<User> {
	
	/**
	 * 
	 * @param user
	 * @return
	 */
	
	public User authenticUser(User user){
		if(user != null){
			return getUserByLoginNamePassword(user.getLoginName(), user.getPassword());
		}
		return null;
	}
	 
	 /**
	  * 
	  * @param emailAddress
	  * @param password
	  * @return
	  */

	public User getUserByLoginNamePassword(String loginName, String password) {
		if (Util.isNullOrEmpty(loginName) || Util.isNullOrEmpty(password)) {
		    return null;
		}
		String encryptPassword = PasswordEncryptionUtil.getEncryptedPassword(password);
		Object[] params = { loginName.toLowerCase(), encryptPassword };
		User user = null;
		try {
		    user = dao.getSingleNamedQueryResult("getUserByLoginNameAndPassword", params);
		} catch (Exception exp) {
		    logger.warn(exp.toString());
		}
		return user;
   }

	public boolean changePassword(User user) {
		User dbUser = getUserByLoginNamePassword(user.getLoginName(), user.getPassword());
		if(dbUser != null){
			dbUser.setPassword(PasswordEncryptionUtil.getEncryptedPassword(user.getNewPassword()));
			merge(dbUser);
			return true;
		}
		return false;
	}

}
